package com.example.utgardtutorial1.client;


import com.example.utgardtutorial1.entity.JinWeiNumericalDetection;
import com.example.utgardtutorial1.entity.SimulationSaveNameOne;
import com.example.utgardtutorial1.mapper.Zhsc1Mapper;
import com.example.utgardtutorial1.service.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.core.IJIUnsigned;
import org.jinterop.dcom.core.JIVariant;
import org.openscada.opc.lib.common.ConnectionInformation;
import org.openscada.opc.lib.common.NotConnectedException;
import org.openscada.opc.lib.da.*;
import org.openscada.opc.lib.da.browser.Branch;
import org.openscada.opc.lib.da.browser.FlatBrowser;
import org.openscada.opc.lib.da.browser.Leaf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@Slf4j
@Component
public class OpcClientGenCp320 {
    @Autowired
    Zhsc1Mapper zhsc1Mapper;
    @Autowired
    Zhsc1Service zhsc1Service;
    @Autowired
    ClsnOpcService clsnOpcService;
    @Autowired
    Cp200Service cp200Service;
    @Autowired
    Cp300Service cp300Service;
    @Autowired
    Cp320Service cp320Service;
    @Autowired
    Cp500Service cp500Service;
    @Autowired
    LsaOpcService lsaOpcService;
    @Autowired
    OtherOpcService otherOpcService;
    @Autowired
    SsbfOpcService ssbfOpcService;
    @Autowired
    TsjOpcService tsjOpcService;
    @Autowired
    WnOpcService wnOpcService;
    @Autowired
    YsbfOpcService ysbfOpcService;
    @Autowired
    YsbzOpcService ysbzOpcService;

    @Autowired
    JinWeiNumericalDetectionService jinWeiNumericalDetectionService;
    @Autowired
    SimulationSaveNameOneService simulationSaveNameOneService;


    //存模拟量保持当前状态的次数
    Map<String,Integer> simulationMapInteger = new HashMap<>();
    //存模拟量保持当前状态的数值
    Map<String,Object> simulationMapObject = new HashMap<>();

    //存模拟量为0的次数
    Map<String,Integer> simulationMapInteger0 = new HashMap<>();

    //存模拟量为null的次数
    Map<String,Integer> simulationMapIntegerNull = new HashMap<>();

    Map<String,Object> stringObjectMap = new HashMap<>();


    List<String> stringList = new ArrayList<>();
/*    @SneakyThrows
    //@PostConstruct
    public void createClient1() {
        long timestamp = System.currentTimeMillis();
        // 时间戳转Date
        Date timeStampDate = new Date(timestamp);
// 时间戳转Calender
        Calendar timeStampCalendar = Calendar.getInstance();
        timeStampCalendar.setTimeInMillis(timestamp);
// 时间戳转String
        String timeStampStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
// 时间戳转LocalDateTime
        LocalDateTime timeStampLocalDateTime =  LocalDateTime.ofEpochSecond(timestamp,0, ZoneOffset.ofHours(8));
        String localDateTime = timeStampLocalDateTime.toString();

        // 连接信
        final ConnectionInformation ci = new ConnectionInformation();
        //ci.setHost("192.168.197.129");         // 本机IP
        ci.setHost("192.168.7.110");         // 本机IP
        ci.setDomain("");                  // 域，为空就行
        ci.setUser("administrator");             // 本机上自己建好的用户名
        ci.setPassword("jbsc@server01");
        ci.setProgId(null);

        // 使用KEPServer的配置
        ci.setClsid("19d98a61-b3ca-4143-0088-35464d714ea0"); // KEPServer的注册表ID，可以在“组件服务”中查到
        List<OpcItems> opcItemsList = new ArrayList<>();
        QueryWrapper<OpcItems> opcItemsQueryWrapper = new QueryWrapper<>();
        //opcItemsQueryWrapper.between("id",0,10);
        opcItemsList = opcItemsService.list(opcItemsQueryWrapper);
        List<String> stringList = opcItemsList.stream().map(OpcItems::getIdentifier).collect(Collectors.toList());
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        opcDaClient = new Server(ci, executor);

        opcDaClient.connect();
    }*/

    AccessBase accessBase;

    Server opcDaClient;

    //津滨

    @SneakyThrows
    //@Scheduled(cron = "0 */3 * * * ?")
    @PostConstruct
    public void createClientsZhsc1() throws InterruptedException {
        stringList =zhsc1Mapper.selectOnlyOpcItemsCp320();
        List<String> simulationItemsOne = zhsc1Mapper.selectSimulationItemsCp320();
        for (String key:simulationItemsOne){
            simulationMapInteger.put(key,0);
            simulationMapInteger0.put(key,0);
            simulationMapIntegerNull.put(key,0);
            simulationMapObject.put(key,"");
        }

        // 连接信
        final ConnectionInformation ci = new ConnectionInformation();
        ci.setHost("192.168.7.110");         // 本机IP
        ci.setDomain("");                  // 域，为空就行
        ci.setUser("administrator");             // 本机上自己建好的用户名
        ci.setPassword("jbsc@server01");
        ci.setProgId(null);
        ci.setClsid("19d98a61-b3ca-4143-0088-35464d714ea0");

        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        opcDaClient = new Server(ci, executor);
/*        try {
            for (String itemId : stringList) {
                accessBase.addItem(itemId, new DataCallback() {
                    @Override
                    public void changed(Item item, ItemState itemState) {
                        JIVariant value1 = itemState.getValue();
                        try {
                            String values = convertValueToString(value1);
                            if (values.equals("")){
                                values = null;
                            }
                            stringObjectMap.put(itemId,values);
                        } catch (JIException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            accessBase.bind();
        } catch (final JIException e) {
            System.out.println(String.format("%08X: %s", e.getErrorCode(), opcDaClient.getErrorMessage(e.getErrorCode())));
        }*/
        AutoReconnectController controller = new AutoReconnectController(opcDaClient);
        accessBase = new SyncAccess(opcDaClient, 120 * 1000);
        controller.addListener(new AutoReconnectListener() {
            @SneakyThrows
            @Override
            public void stateChanged(AutoReconnectState autoReconnectState) {
                System.out.println("重连");
                try {
                    subscribeItems();
                    System.out.println("重连成功");
                } catch (JIException e) {
                    throw new RuntimeException(e);
                } catch (AddFailedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        controller.connect();
    }

    private void dumpFlat(final FlatBrowser browser)
            throws IllegalArgumentException, UnknownHostException, JIException {
        for (String name : browser.browse()) {
            System.out.println(name);
        }
    }

    // 在重连成功后调用此方法
    private void subscribeItems() throws JIException, AddFailedException, DuplicateGroupException, UnknownHostException, NotConnectedException {
        System.out.println("试图重连");
        accessBase = new SyncAccess(opcDaClient, 120 * 1000);
        accessBase.clear();

        for (String itemId : stringList) {
            accessBase.addItem(itemId, new DataCallback() {
                @Override
                public void changed(Item item, ItemState itemState) {
                    JIVariant value1 = itemState.getValue();
                    try {
                        String values = convertValueToString(value1);
                        if (values.equals("")){
                            values = null;
                        }
                        stringObjectMap.put(itemId,values);
                    } catch (JIException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        accessBase.bind();
        System.out.println("重连读数开始");
    }

    @Scheduled(cron = "0 */3 * * * ?")
    private void saveDaguhe(){
        System.out.println("save start");
                Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR_OF_DAY,8);
        date = calendar.getTime();
        List<SimulationSaveNameOne> simulationSaveNameOnes = simulationSaveNameOneService.list();
        List<String> simulationItemsOne = zhsc1Mapper.selectSimulationItemsCp320();
        Map<String,Object> objectMap = stringObjectMap;
        List<JinWeiNumericalDetection> jinWeiNumericalDetections = new ArrayList<>();
        for (String key : objectMap.keySet()){
            if (simulationItemsOne.contains(key)){
                for (SimulationSaveNameOne simulationSaveNameOne : simulationSaveNameOnes) {
                    if (key.equals("JBSC." + simulationSaveNameOne.getColumnName())) {
                        //无实时值NULL
                        if (ObjectUtils.isEmpty(objectMap.get(key))||objectMap.get(key).equals(null)){

                            simulationMapInteger.put(key, 0);
                            simulationMapInteger0.put(key, 0);
                            simulationMapIntegerNull.put(key,simulationMapIntegerNull.get(key)+1);
                            continue;
                        }//不是就替换
                        else {
                            simulationMapIntegerNull.put(key,0);
                        }
                        //100次后
                        if (simulationMapIntegerNull.get(key) == 100){
                            JinWeiNumericalDetection jinWeiNumericalDetection = new JinWeiNumericalDetection();
                            jinWeiNumericalDetection.setColumnName(simulationSaveNameOne.getColumnName());
                            jinWeiNumericalDetection.setComment(simulationSaveNameOne.getComment());
                            jinWeiNumericalDetection.setDepartment("津滨水厂");
                            jinWeiNumericalDetection.setProcessSystem("一期");
                            jinWeiNumericalDetection.setEngUnits(simulationSaveNameOne.getEngUnits());
                            //jinWeiNumericalDetection.setNumber(new BigDecimal(objectMap.get(key).toString()));
                            jinWeiNumericalDetection.setDate1(date);
                            jinWeiNumericalDetection.setDate2(date);
                            jinWeiNumericalDetection.setQuestionType("无实时值NULL100次");
                            jinWeiNumericalDetections.add(jinWeiNumericalDetection);
                            simulationMapIntegerNull.put(key,1);
                        }

                        //数据为0
                        if ((!ObjectUtils.isEmpty(objectMap.get(key))&&!objectMap.get(key).equals(null))&&new BigDecimal(objectMap.get(key).toString()).equals(new BigDecimal(0))){

                            simulationMapInteger0.put(key,simulationMapInteger0.get(key)+1);
                            simulationMapInteger.put(key,0);

                            //jinWeiNumericalDetections.add(jinWeiNumericalDetection);
                        } else {
                            //不一样替换
                            simulationMapInteger0.put(key,0);
                        }

                        if (simulationMapInteger0.get(key) == 100) {
                            JinWeiNumericalDetection jinWeiNumericalDetection = new JinWeiNumericalDetection();
                            jinWeiNumericalDetection.setColumnName(simulationSaveNameOne.getColumnName());
                            jinWeiNumericalDetection.setComment(simulationSaveNameOne.getComment());
                            jinWeiNumericalDetection.setDepartment("津滨水厂");
                            jinWeiNumericalDetection.setProcessSystem("一期");
                            jinWeiNumericalDetection.setEngUnits(simulationSaveNameOne.getEngUnits());
                            jinWeiNumericalDetection.setNumber(new BigDecimal(objectMap.get(key).toString()));
                            jinWeiNumericalDetection.setDate1(date);
                            jinWeiNumericalDetection.setDate2(date);
                            jinWeiNumericalDetection.setQuestionType("100次数据为0");
                            jinWeiNumericalDetections.add(jinWeiNumericalDetection);
                            simulationMapInteger0.put(key, 0);
                            //simulationMapInteger0.put(key,simulationMapInteger0.get(key)+1);
                        }

                        //100次数据不变
                        //如果内容一样加1
                        //System.out.println(objectMap.get(key));
                        //System.out.println(simulationMapObject.get(key));
                        if ((!ObjectUtils.isEmpty(objectMap.get(key))&&!objectMap.get(key).equals(null))
                                &&simulationMapObject.get(key)
                                .equals(objectMap.get(key))) {
                            simulationMapInteger.put(key, simulationMapInteger.get(key) + 1);
                        } else {
                            //不一样替换
                            simulationMapObject.put(key, objectMap.get(key));
                            simulationMapInteger.put(key, 1);
                        }
                        if (simulationMapInteger.get(key) == 100) {
                            JinWeiNumericalDetection jinWeiNumericalDetection = new JinWeiNumericalDetection();
                            jinWeiNumericalDetection.setColumnName(simulationSaveNameOne.getColumnName());
                            jinWeiNumericalDetection.setComment(simulationSaveNameOne.getComment());
                            jinWeiNumericalDetection.setDepartment("津滨水厂");
                            jinWeiNumericalDetection.setProcessSystem("一期");
                            jinWeiNumericalDetection.setEngUnits(simulationSaveNameOne.getEngUnits());
                            jinWeiNumericalDetection.setNumber(new BigDecimal(objectMap.get(key).toString()));
                            jinWeiNumericalDetection.setDate1(date);
                            jinWeiNumericalDetection.setDate2(date);
                            jinWeiNumericalDetection.setQuestionType("100次数据不变");
                            simulationMapInteger.put(key, 0);
                            jinWeiNumericalDetections.add(jinWeiNumericalDetection);
                        }


                    }
                }            }
            if (!ObjectUtils.isEmpty(objectMap.get(key))) {
                if (objectMap.get(key).toString().equals("false")) {
                    objectMap.put(key, 0);
                }
                if (objectMap.get(key).toString().equals("true")) {
                    objectMap.put(key, 1);
                }
            }

        }
        System.out.println("_________开始");
        //zhsc1Service.saveMap(objectMap);
        //clsnOpcService.saveMap(objectMap);
        //cp200Service.saveMap(objectMap);
        //cp300Service.saveMap(objectMap);
        cp320Service.saveMap(objectMap);
/*
        cp500Service.saveMap(objectMap);
        lsaOpcService.saveMap(objectMap);
        otherOpcService.saveMap(objectMap);
        ssbfOpcService.saveMap(objectMap);
        tsjOpcService.saveMap(objectMap);
        wnOpcService.saveMap(objectMap);
        ysbfOpcService.saveMap(objectMap);
        ysbzOpcService.saveMap(objectMap);*/
        jinWeiNumericalDetectionService.saveBatch(jinWeiNumericalDetections);
    }


    private static String printTab(int level) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < level; i++) {
            sb.append("\t");
        }
        return sb.toString();
    }

    /**
     * 打印Item
     *
     * @param leaf
     */
    private static void dumpLeaf(final Leaf leaf, final int level) {
        System.out.println(printTab(level) + "Leaf: " + leaf.getName() + ":"
                + leaf.getItemId());
    }

    /**
     * 打印Group
     *
     * @param branch
     */
    private static void dumpBranch(final Branch branch, final int level) {
        System.out.println(printTab(level) + "Branch: " + branch.getName());
    }

    public String convertValueToString(JIVariant value) throws JIException {
        String result = "";
        int type = value.getType();
        if (type == JIVariant.VT_I4) {
            int n = value.getObjectAsInt();
            result = String.valueOf(n);
        }
        if (type == JIVariant.VT_UI4) {
            IJIUnsigned n = value.getObjectAsUnsigned();
            result = String.valueOf(n.getValue().intValue());
        }
        if (type == JIVariant.VT_R4) {
            float n = value.getObjectAsFloat();
            result = String.valueOf(n);
        }
        if (type == JIVariant.VT_BOOL) {
            boolean n = value.getObjectAsBoolean();
            result = String.valueOf(n);
        }

        if (type == JIVariant.VT_R8) {
            double n = value.getObjectAsDouble();
            result = String.valueOf(n);
        }
        if (type == JIVariant.VT_I2) {
            short n = value.getObjectAsShort();
            result = String.valueOf(n);
        }
        if (type == JIVariant.VT_UI2) {
            IJIUnsigned n = value.getObjectAsUnsigned();
            result = String.valueOf(n.getValue().shortValue());
        }
        if (type == JIVariant.VT_I1) {
            char n = value.getObjectAsChar();
            result = String.valueOf(n);
        }
        return result;
    }
}
